//
//  ErDuFriendVC.m
//  BrushFace
//
//  Created by timer_q on 16/1/11.
//  Copyright © 2016年 Zzz. All rights reserved.
//

#import "AddAddressBookFriendVC.h"
#import "AddFriendCell.h"
#import "NavHelper.h"
#import "ContactViewModel.h"
#import <MessageUI/MessageUI.h>
#import "SearchResultVC.h"
@interface AddAddressBookFriendVC ()<UITableViewDelegate,UITableViewDataSource,MFMessageComposeViewControllerDelegate>
{
    NSMutableDictionary                 *contactInfoDic;
    NSMutableArray                      *indexArray;
    UITableView                         *_tableView;
}
@property (nonatomic, strong)ContactViewModel *viewModel;
@end

@implementation AddAddressBookFriendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UIConfig];
    [self dataInit];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.viewModel fetchAllFriendInAddressBookAndCB:^(id output) {
        contactInfoDic = output;
        [indexArray removeAllObjects];
        NSArray *array = [output allKeys];
        array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            NSComparisonResult result = [obj1 compare:obj2];
            return result==NSOrderedDescending;
        }];
        [indexArray addObjectsFromArray:array];
        [_tableView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - customMethods
- (void)UIConfig{
    
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    [self.navBar setTitle:@"手机联系人"];
    self.view.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, SCREEN_HEIGHT-65) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.sectionIndexColor = [UIColor grayColor];
    _tableView.sectionIndexBackgroundColor= [UIColor clearColor];
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];
    
}
- (void)dataInit{
    indexArray = [[NSMutableArray alloc] init];
    _viewModel = [ContactViewModel SceneModel];
}
#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * header = [[UIView alloc] init];
    header.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 100, 30)];
    label.text = indexArray[section];
    [header addSubview:label];
    return header;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return indexArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[section]]] count];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return nil;
    }
    return indexArray;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    //点击索引，列表跳转到对应索引的行
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddFriendCell *cell = [AddFriendCell loadBundleNib];
    NSDictionary *dict = [contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row];
    cell.nickNameLabel.text = [dict objectForKey:@"friendname"];
    cell.phoneNameLabel.text = [NSString stringWithFormat:@"手机联系人：%@",[dict objectForKey:@"friendname"]];
    [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,[dict objectForKey:@"frienduserid"]]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    NSInteger statu = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]] integerValue];
    cell.statu = statu;
    cell.phone = [NSString stringWithFormat:@"%@",dict[@"friendphone"]];
    cell.friendId = [NSString stringWithFormat:@"%@",dict[@"frienduserid"]];
    cell.target = self;
    cell.msgid = dict[@"id"];
    switch (statu) {
        case 0:
        {
            [cell.statuBtn setImage:[UIImage imageNamed:@"yaoqingBtn"] forState:UIControlStateNormal];
            cell.statulabel.hidden = YES;
            cell.statuBtn.hidden = NO;
        }
            break;
        case 1:
        {
            cell.statulabel.hidden = YES;
            cell.statuBtn.hidden = NO;
            [cell.statuBtn setImage:[UIImage imageNamed:@"addfrienddetail"] forState:UIControlStateNormal];
        }
            break;
        case 2:
        {
            cell.statulabel.text = @"待通过";
            cell.statulabel.hidden = NO;
            cell.statuBtn.hidden = YES;
        }
            break;
        case 3:
        {
            cell.statuBtn.hidden = NO;
            cell.statulabel.hidden = YES;
            [cell.statuBtn setImage:[UIImage imageNamed:@"jieshou"] forState:UIControlStateNormal];
        }
            break;
        case 4:
        {
            cell.statulabel.text = @"已添加";
            cell.statulabel.hidden = NO;
            cell.statuBtn.hidden = YES;
        }
            break;
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = [contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row];
    NSInteger statu = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]] integerValue];
    NSString *friendId = dict[@"frienduserid"];
    switch (statu) {
        case 0:
        {return;}break;
        case 1:
        {
            SearchResultVC *resultVC = [[SearchResultVC alloc] init];
            resultVC.source = @"通讯录匹配";
            resultVC.userid = friendId;
            [resultVC setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:resultVC animated:YES];
        }
            break;
        case 2:
        {
            SearchResultVC *resultVC = [[SearchResultVC alloc] init];
            resultVC.source = @"通讯录匹配";
            resultVC.userid = friendId;
            [resultVC setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:resultVC animated:YES];
        }
            break;
        case 3:
        {
            [NavHelper gotoPassFriendVCWithUserID:dict[@"id"]];
        }
            break;
        case 4:
        {
            [NavHelper gotoContactDetailVCWithUserId:friendId];
        }
            break;
        default:
            break;
    }
   

}

- (NSString *)replayBaseStr:(NSString *)nickName{
    NSMutableString *nickN = [[NSMutableString alloc]initWithString:nickName];
    NSMutableString *retStr = [[NSMutableString alloc] init];
    for (int i=0; i<nickN.length; i+=4) {
        NSString *subStr = [NSString stringWithFormat:@"\\u%@",[nickN substringWithRange:NSMakeRange(i, 4)]];
        [retStr appendString:[self replaceUnicode:subStr]];
    }
    return retStr;
}

- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    switch (result)
    {
        case MessageComposeResultCancelled:
            //LOG_EXPR(@"Result: SMS sending canceled");
            break;
        case MessageComposeResultSent:
        {
            
        }
            break;
        case MessageComposeResultFailed:
        {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发送失败" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alert show];
        }
            break;
        default:
            //LOG_EXPR(@"Result: SMS not sent");
            break;
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

@end
